
export const state = () => ({
  deptList: [], // 一、二级列表
  deptMaps: {},
  deptListMaps: {}, // 一级id: 二级列表

  areaList: [], // 二、三级列表
  areaMaps: {},
  areaListMaps: {}, // 二级id: 三级列表

  teacherList: [],
  teacherMaps: {}
})

export const mutations = {

  SET_DEPT (state, list = []) {
    state.deptMaps = {}
    const { deptList, deptMaps } = state
    deptList.splice(0)
    list.forEach(i => {
      const { deptId } = i
      deptList.push(i)
      deptMaps[deptId] = i
    })
  },

  SET_AREA (state, list = []) {
    state.areaMaps = {}
    state.areaListMaps = {}
    state.deptListMaps = {}
    const { areaList, areaMaps, areaListMaps, deptListMaps } = state
    areaList.splice(0)
    list.forEach(i => {
      const { areaPid, areaId, areaName, deptId } = i
      i.id = areaId
      i.name = areaName
      if (areaPid > 0) {
        if (!areaListMaps[areaPid]) areaListMaps[areaPid] = []
        areaListMaps[areaPid].push(i)
      } else {
        i.children = []
        if (!deptListMaps[deptId]) deptListMaps[deptId] = []
        deptListMaps[deptId].push(i)
      }
      areaList.push(i)
      areaMaps[areaId] = i
    })
  },

  SET_DEPT_AREA (state) {
    const { deptListMaps, areaListMaps } = state
    const { $get } = this
    for (const deptId in deptListMaps) {
      const list = deptListMaps[deptId]
      list.forEach(i => {
        const children = $get(areaListMaps, i.areaId, [])
        Object.assign(i, { children })
      })
    }
  },

  SET_TEACHER (state, list = []) {
    state.teacherMaps = {}
    const { teacherList, teacherMaps } = state
    teacherList.splice(0)
    list.forEach(i => {
      teacherList.push(i)
      if (i.userId) teacherMaps[i.userId] = i
    })
  }
}

export const actions = {
  setAreaList ({ commit }, list = []) {
    commit('SET_AREA', list)
  },

  setDeptList ({ commit }, list = []) {
    commit('SET_DEPT', list)
  },

  setDeptArea ({ commit }) {
    commit('SET_DEPT_AREA')
  },

  setTeacherList  ({ commit }, list = []) {
    commit('SET_TEACHER', list)
  }
}
